//
//  SecurityManager.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import Foundation
import Security
import WebKit

class SecurityManager {
    
    // MARK: - Cookie 存储
    
    /// 保存Cookie到Keychain
    static func saveCookies(_ cookies: [HTTPCookie], for boxId: UUID) {
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: cookies, requiringSecureCoding: true)
            saveToKeychain(data: data, service: "cookies", account: boxId.uuidString)
        } catch {
            print("保存Cookie失败: \(error)")
        }
    }
    
    /// 从Keychain加载Cookie
    static func loadCookies(for boxId: UUID) -> [HTTPCookie]? {
        guard let data = loadFromKeychain(service: "cookies", account: boxId.uuidString) else {
            return nil
        }
        
        do {
            guard let cookies = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: data) as? [HTTPCookie] else {
                return nil
            }
            return cookies
        } catch {
            print("加载Cookie失败: \(error)")
            return nil
        }
    }
    
    /// 删除指定盒子的Cookie
    static func deleteCookies(for boxId: UUID) {
        deleteFromKeychain(service: "cookies", account: boxId.uuidString)
    }
    
    // MARK: - Token 存储
    
    /// 保存Token到Keychain
    static func saveToken(_ token: String, for boxId: UUID, key: String) {
        guard let data = token.data(using: .utf8) else { return }
        saveToKeychain(data: data, service: "tokens", account: "\(boxId.uuidString)_\(key)")
    }
    
    /// 从Keychain加载Token
    static func loadToken(for boxId: UUID, key: String) -> String? {
        guard let data = loadFromKeychain(service: "tokens", account: "\(boxId.uuidString)_\(key)") else {
            return nil
        }
        return String(data: data, encoding: .utf8)
    }
    
    /// 删除指定Token
    static func deleteToken(for boxId: UUID, key: String) {
        deleteFromKeychain(service: "tokens", account: "\(boxId.uuidString)_\(key)")
    }
    
    // MARK: - 通用Keychain操作
    
    private static func saveToKeychain(data: Data, service: String, account: String) {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
        ]
        
        // 先删除现有项
        deleteFromKeychain(service: service, account: account)
        
        // 添加新项
        let status = SecItemAdd(query as CFDictionary, nil)
        guard status == errSecSuccess else {
            print("Keychain保存失败: \(status)")
            return
        }
    }
    
    private static func loadFromKeychain(service: String, account: String) -> Data? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        
        guard status == errSecSuccess, let data = result as? Data else {
            return nil
        }
        
        return data
    }
    
    private static func deleteFromKeychain(service: String, account: String) {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account
        ]
        
        SecItemDelete(query as CFDictionary)
    }
}